<template>
  <div class="pagination">
    <!-- emm,不知道说什么好，这里应该使用pageNo，从父组件接收的数据 -->
    <button @click="goPage(pageNo-1)" :disabled="pageNo==1">上一页</button>
    <button v-if="pageStartAndPageEnd.start>1" @click="goPage(1)" :class="{active:pageNo==1}">1</button>
    <button v-if="pageStartAndPageEnd.start>2">...</button>
    <!-- v-if与v-for同时使用会报错（报错原因：意味着每条循环语句都会被v-if，虽然不影响使用）。。。但是，报红色会很难受。可以使用以下方法 -->
    <template v-for="(page,index) in pageStartAndPageEnd.end" :class="{active:page==pageNo}">
      <button v-if="page>=pageStartAndPageEnd.start" :key="index" @click="goPage(page)" :class="{active:page==pageNo}">{{page}}</button>
    </template>
    <button v-if="pageStartAndPageEnd.end<totalpage-1">...</button>
    <button v-if="pageStartAndPageEnd.end<totalpage" @click="goPage(totalpage)" :class="{active:pageNo==totalpage}">{{totalpage}}</button>
    <button @click="goPage(pageNo+1)" :disabled="pageNo==totalpage">下一页</button>
    <button style="margin-left: 30px">共 {{total}} 条</button>
  </div>
</template>
<script>
export default {
  name: "pagination",
  props:["pageNo","pageSize","total","continues"],
  methods: {
    // goPre(){
    //   this.$emit("goPre")
    // },
    // goNext(){
    //   this.$emit("goNext")
    // },
    goPage(page){
      this.$emit("goPage",page)
    }
  },
  computed:{
    //总页数
   totalpage(){
     //向上取整
     return Math.ceil(this.total/this.pageSize);
   },
   pageStartAndPageEnd(){
     const {pageNo,continues,totalpage}=this;
     let start=1;
     let end=1;
     start=pageNo-parseInt(continues/2);
     end=pageNo+parseInt(continues/2);
     if (start<1) {
       start=1;
       end=continues;
     }
     if (end>totalpage) {
       start=totalpage-continues+1;
       end=totalpage;
     }
     return {start,end}
   }
  }
};
</script>
<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
.active {
  background: skyblue;
}
</style>